import { computed, ref } from 'vue';
import router from '@/router';
import { defineStore } from 'pinia';
import { getInfoApi, loginApi } from '@/api/login';
import { USER_STORE } from '../constant';
import { usePermissionsStore } from './permissions';
import { useTabViewsStore } from './tabViews';

export const useUserStore = defineStore(
  USER_STORE,
  () => {
    const token = ref<string>('');
    const roles = ref<string[]>([]);
    const user = ref<Record<string, any>>({});
    const permissions = ref<string[]>([]);

    const userId = computed(() => user.value?.userId || '');
    const userName = computed(() => user.value?.userName || '');
    const avatar = computed(() => user.value?.avatar || '');
    const isAdmin = computed(() => !!user.value?.admin);

    const login = async (state: any) => {
      const res = await loginApi(state);
      token.value = (res as any).token;
    };

    const getUserInfo = async () => {
      const res = await getInfoApi();
      user.value = (res as any).user;
      roles.value = (res as any).roles || ['ROLE_DEFAULT'];
      permissions.value = (res as any).permissions;
    };

    const logout = async () => {
      token.value = '';
      user.value = {};
      permissions.value = [];
      const permissionStore = usePermissionsStore();
      permissionStore.cleanMenus();
      const tabViewsStore = useTabViewsStore();
      tabViewsStore.closeAllTab();

      roles.value = [];
      router.replace('/login');
    };

    const setToken = (_token: string) => {
      token.value = _token;
    };

    return {
      token,
      roles,
      user,
      userId,
      userName,
      avatar,
      permissions,
      isAdmin,
      login,
      logout,
      getUserInfo,
      setToken,
    };
  },
  {
    persist: {
      paths: ['token'],
    },
  },
);
